import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

public class EasyExcel2Test {


    public static void main(String[] args) throws IOException {
        // 创建一个新的Excel工作簿
        Workbook workbook = new XSSFWorkbook();

        // 添加一个工作表
        Sheet sheet = workbook.createSheet("打卡报表");

        // 主标题
        String mainTitle = "打卡报表";

        // 随机生成副标题列表
        List<String> subTitles = List.of("序号", "车辆名称", "车牌号", "司机名称", "打卡时间", "打卡位置"); // 示例中生成3个副标题，您可以根据需求调整

        // 合并副标题数量的单元格作为主标题区域
        int firstRowNum = 0;
        int lastRowNum = 0;
        int firstColNum = 0;
        int lastColNum = subTitles.size() - 1;

        Row row = sheet.createRow(firstRowNum);
        Cell cell = row.createCell(firstColNum);
        cell.setCellValue(mainTitle);

        CellRangeAddress titleRange = new CellRangeAddress(firstRowNum, lastRowNum, firstColNum, lastColNum);
        sheet.addMergedRegion(titleRange);


        // 设置主标题样式（居中显示）
        CellStyle titleCellStyle = workbook.createCellStyle();
        titleCellStyle.setAlignment(HorizontalAlignment.CENTER);
        titleCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 添加边框样式
        titleCellStyle.setBorderTop(BorderStyle.THIN);
        titleCellStyle.setBorderBottom(BorderStyle.THIN);
        titleCellStyle.setBorderLeft(BorderStyle.THIN);
        titleCellStyle.setBorderRight(BorderStyle.THIN);

        // 创建RichTextString，设置“打卡”两字加粗且字号比“报表”两字大3号
        XSSFRichTextString richTextTitle = new XSSFRichTextString(mainTitle);

        // 获取“打卡”两字的起始和结束位置
        int checkInStart = 0;
        int checkInEnd = 2;

        // 获取“报表”两字的起始和结束位置
        int reportStart = 2;
        int reportEnd = 4;

        // 创建用于“打卡”的加粗、大号字体
        Font checkInFont = workbook.createFont();
        checkInFont.setBold(true);
        int baseFontSize = workbook.getFontAt(cell.getCellStyle().getFontIndex()).getFontHeightInPoints();
        checkInFont.setFontHeightInPoints((short) ((short) baseFontSize + 3)); // 比基础字号大3号

        // 将“打卡”两字应用加粗、大号字体
        richTextTitle.applyFont(checkInStart, checkInEnd, checkInFont);

        // 将设置好的RichTextString写入单元格
        cell.setCellValue(richTextTitle);

        cell.setCellStyle(titleCellStyle);

        // 设置主标题行高为40
        row.setHeightInPoints(40);
        // 写入副标题
        writeSubTitles(sheet, subTitles);

        // 写入副标题（全部在第二行的不同列）
        int rowIndex = 1;
        for (int colIndex = 0; colIndex < subTitles.size(); colIndex++) {
            String subTitle = subTitles.get(colIndex);
            Row subTitleRow = sheet.getRow(rowIndex) != null ? sheet.getRow(rowIndex) : sheet.createRow(rowIndex);
            Cell subTitleCell = subTitleRow.createCell(colIndex);
            subTitleCell.setCellValue(subTitle);

            // 设置副标题样式（居中显示、蓝色背景、加粗字体）
            CellStyle subTitleCellStyle = workbook.createCellStyle();
            subTitleCellStyle.setAlignment(HorizontalAlignment.CENTER);

            // 设置背景色为蓝色
            subTitleCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
            subTitleCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            subTitleCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 设置字体加粗
            Font boldFont = workbook.createFont();
            boldFont.setBold(true);
            subTitleCellStyle.setFont(boldFont);

            // 添加边框样式
            subTitleCellStyle.setBorderTop(BorderStyle.THIN);
            subTitleCellStyle.setBorderBottom(BorderStyle.THIN);
            subTitleCellStyle.setBorderLeft(BorderStyle.THIN);
            subTitleCellStyle.setBorderRight(BorderStyle.THIN);

            subTitleCell.setCellStyle(subTitleCellStyle);

            // 设置副标题行高为20
            subTitleRow.setHeightInPoints(20);
        }

        // 设置所有行宽度自动适应内容
        for (int i = 0; i <= subTitles.size(); i++) {
            sheet.setColumnWidth(i, 18 * 256);
        }

        // 写入当前Sheet的数据
        generateAndWriteDataRows(sheet, subTitles, 2, 100);

        // 写入Excel文件
        try (FileOutputStream outputStream = new FileOutputStream("CheckInReport.xlsx")) {
            workbook.write(outputStream);
        }

        // 关闭工作簿
        workbook.close();
    }

    private static void writeSubTitles(Sheet sheet, List<String> subTitles) {
        // 写入副标题（全部在第二行的不同列）
        int rowIndex = 1;
        for (int colIndex = 0; colIndex < subTitles.size(); colIndex++) {
            String subTitle = subTitles.get(colIndex);
            Row subTitleRow = sheet.getRow(rowIndex) != null ? sheet.getRow(rowIndex) : sheet.createRow(rowIndex);
            Cell subTitleCell = subTitleRow.createCell(colIndex);
            subTitleCell.setCellValue(subTitle);

            // 设置副标题样式（居中显示、蓝色背景、加粗字体、边框）
            CellStyle subTitleCellStyle = sheet.getWorkbook().createCellStyle();
            subTitleCellStyle.setAlignment(HorizontalAlignment.CENTER);
            subTitleCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 设置背景色为蓝色
            subTitleCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
            subTitleCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            // 设置字体加粗
            Font boldFont = sheet.getWorkbook().createFont();
            boldFont.setBold(true);
            subTitleCellStyle.setFont(boldFont);

            // 添加边框样式
            subTitleCellStyle.setBorderTop(BorderStyle.THIN);
            subTitleCellStyle.setBorderBottom(BorderStyle.THIN);
            subTitleCellStyle.setBorderLeft(BorderStyle.THIN);
            subTitleCellStyle.setBorderRight(BorderStyle.THIN);

            subTitleCell.setCellStyle(subTitleCellStyle);

            // 设置副标题行高为20
            subTitleRow.setHeightInPoints(20);
        }
    }

    private static void generateAndWriteDataRows(Sheet sheet, List<String> subTitles, int startRowIndex, int rowCount) {
        // 随机生成数据
        Random random = new Random();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (int rowIndex = startRowIndex; rowIndex < startRowIndex + rowCount; rowIndex++) {
            Row dataRow = sheet.getRow(rowIndex) != null ? sheet.getRow(rowIndex) : sheet.createRow(rowIndex);

            // 生成随机数据
            int sequence = rowIndex - startRowIndex + 1;
            String vehicleName = "车辆" + sequence;
            String plateNumber = "车牌" + String.format("%02d", sequence);
            String driverName = "司机" + sequence;
            LocalDateTime checkInTime = LocalDateTime.now().minusDays(random.nextInt(7)).minusHours(random.nextInt(24));
            String formattedCheckInTime = checkInTime.format(formatter);
            String checkInLocation = "位置" + sequence;

            // 创建居中对齐的单元格样式
            CellStyle dataCellStyle = sheet.getWorkbook().createCellStyle();
            dataCellStyle.setAlignment(HorizontalAlignment.CENTER);
            dataCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 写入数据
            for (int colIndex = 0; colIndex < subTitles.size(); colIndex++) {
                String subTitle = subTitles.get(colIndex);
                Cell cell = dataRow.getCell(colIndex) != null ? dataRow.getCell(colIndex) : dataRow.createCell(colIndex);

                switch (subTitle) {
                    case "序号":
                        cell.setCellValue(sequence);
                        break;
                    case "车辆名称":
                        cell.setCellValue(vehicleName);
                        break;
                    case "车牌号":
                        cell.setCellValue(plateNumber);
                        break;
                    case "司机名称":
                        cell.setCellValue(driverName);
                        break;
                    case "打卡时间":
                        cell.setCellValue(formattedCheckInTime);
                        break;
                    case "打卡位置":
                        cell.setCellValue(checkInLocation);
                        break;
                }
                cell.setCellStyle(dataCellStyle);
            }
        }
    }

}